import json
import time
import traceback

import requests
import websocket
from loguru import logger


def connect():
    deviceName = "EV982EEA9821440576"
    # 创建 WebSocket 客户端对象
    ws = websocket.WebSocket()
    ip = "192.168.0.6"
    # 连接到 WebSocket 服务器
    ws.connect("ws://{}:8555/api".format(ip))
    # 获取当前卡
    ws.send('{"command":"GetCBCurrSim_Multi","arguments":{"devicename":"' + deviceName + '"}}')
    result_text = ws.recv()
    logger.info("获取当前卡返回：【{}】", result_text)
    result_data = json.loads(result_text)
    if result_data['data']['invoke_command'] == "GetCBCurrSim_Multi":
        simid = result_data['dynamicdata']['simid']
        post_gate_info(deviceName, simid)
    # 发送消息
    ws.send('''{"command":"GetSMS"}''')
    result_text = ws.recv()
    logger.info("接收返回：【{}】", result_text)
    result_data = json.loads(result_text)
    if 'dynamicdata' in result_data and result_data['dynamicdata'] is not None and len(result_data['dynamicdata']) > 0:
        count = len(result_data['dynamicdata'])
        for i in range(count):
            content = result_data['dynamicdata'][i]['content']
            smsid = result_data['dynamicdata'][i]['smsid']
            print("正在推送短信内容...")
            post_data(content, deviceName)
            ws.send('''{"command":"DeleteSMSBySmsID","arguments":{"content":"''' + smsid + '''"}}''')
    post_heart(ip)
    # 关闭连接
    ws.close()


def post_heart(ip):
    url = "http://1.95.166.150:8997/api/v1/sms/heart"
    data = {
        "phoneOrIp": ip,
        "type": "嗨玩购短信"
    }
    try:
        # logger.info("发送心跳")
        requests.post(url, json=data)
    except Exception as e:
        logger.info(e)

def post_data(content, deviceName):
    url = "http://1.95.166.150:8997/api/v1/sms/mutilSave"
    data = {
        "deviceName": deviceName,
        "text": content
    }
    print("参数：{}".format(data))
    try:
        requests.post(url, json=data)
    except:
        traceback.print_exc()


def post_gate_info(device_name, simid):
    url = "http://1.95.166.150:8997/api/v1/device/gateInfo/{}/{}".format(device_name, str(simid))
    print("参数：{}，{}".format(device_name, simid))
    try:
        requests.get(url)
    except:
        traceback.print_exc()


while 1:
    try:
        connect()
    except:
        traceback.print_exc()
        logger.error("连接失败")
    time.sleep(5)
